<!-- eslint-disable prettier/prettier -->
<template>
  <div>
    <!--顶部搜索-->
    <div class="list-card-operation">
      <div class="button">
        <!--<t-button @click="formDialogVisible = true"> {{ $t('pages.listCard.create') }} </t-button>-->
        <t-button @click="toCart"> {{ $t('pages.listCard.toCart') }} </t-button>
        <t-button variant="outline" theme="primary" @click="toAll"> 全部 </t-button>
        <t-button variant="outline" theme="primary" @click="toProd"> 商品 </t-button>
        <t-button variant="outline" theme="primary" @click="toServ"> 服务 </t-button>
      </div>
      <div class="search-input">
        <t-input v-model="searchValue" :placeholder="$t('pages.listCard.placeholder')" clearable @input="handleInput">
          <template #suffix-icon>
            <search-icon v-if="searchValue === ''" size="var(--td-comp-size-xxxs)" />
          </template>
        </t-input>
      </div>
    </div>
    <!--
    <dialog-form v-model:visible="formDialogVisible" :data="formData" />
    -->
    
    <!--根据表格布局放置卡片-->
    <template v-if="pagination.total > 0 && !dataLoading">
      <div class="list-card-items">
        <t-row :gutter="[16, 16]">
          <t-col v-for="product in productList.slice(
            pagination.pageSize * (pagination.current - 1),
            pagination.pageSize * pagination.current,
          )" :key="product.index" :lg="4" :xs="6" :xl="3">
            <product-card class="list-card-item" :product="product" />
          </t-col>
        </t-row>
      </div>
      <div class="list-card-pagination">
        <t-pagination v-model="pagination.current" v-model:page-size="pagination.pageSize" :total="pagination.total"
          :page-size-options="[12, 24, 36]" @page-size-change="onPageSizeChange" @current-change="onCurrentChange" />
      </div>
    </template>

    <div v-else-if="dataLoading" class="list-card-loading">
      <t-loading size="large" text="加载数据中..." />
    </div>


  </div>
</template>

<script lang="ts">
export default {
  name: 'ListCard',
};
</script>

<script setup lang="ts">
import axios from 'axios';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import { getGoodsCardList, getProductCardList, getServiceCardList } from '@/api/list';
import type { CardProductType } from '@/components/product-card/index.vue';
import ProductCard from '@/components/product-card/index.vue';
import router from '@/router';

import type { FormData } from './components/DialogForm.vue';
import DialogForm from './components/DialogForm.vue';

const INITIAL_DATA: FormData = {
  name: '',
  status: '',
  description: '',
  type: '0',
  mark: '',
  amount: 0,
};

const pagination = ref({ current: 1, pageSize: 12, total: 0 });
// const deleteProduct = ref(undefined);

const productList = ref([]);
const dataLoading = ref(true);

const fetchData = async () => {
  console.log("fetchData")
  try {
    console.log("fetchData1")
    // 请求数据并获取响应
    const response = await axios.get("/api/user/getItems");

    // 从返回的响应中提取数据
    const list = response.data.data.list;
    console.log(list);
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    // 错误处理
    console.log(e);
  } finally {
    // 数据加载完毕
    dataLoading.value = false;
  }
};

onMounted(() => {
  fetchData();
});

const formDialogVisible = ref(false);
const searchValue = ref('');
const confirmVisible = ref(false);
const formData = ref({ ...INITIAL_DATA });

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
};
/* const handleDeleteItem = (product: CardProductType) => {
  confirmVisible.value = true;
  deleteProduct.value = product;
};
const onConfirmDelete = () => {
  const { index } = deleteProduct.value;
  productList.value.splice(index - 1, 1);
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
};
const onCancel = () => {
  deleteProduct.value = undefined;
  formData.value = { ...INITIAL_DATA };
};
  const handleManageProduct = (product: CardProductType) => {
  formDialogVisible.value = true;
  formData.value = {
    name: product.name,
    status: product?.isProduct ? '1' : '0',
    description: product.description,
    type: product.type.toString(),
    mark: '',
    amount: 0,
  };
}; */
const toCart = () => {
  router.push('/shop/cart');
};
const toAll = async () => {
  try {
    const response = await axios.get("/api/user/getItems");

    const list = response.data.data.list;;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };

  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const toProd = async () => {
  try {
    const response = await axios.get("/api/user/getItems?type=item");

    // 从返回的响应中提取数据
    const list = response.data.data.list;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const toServ = async () => {
  try {
    const response = await axios.get("/api/user/getItems?type=service");
    
    // 从返回的响应中提取数据
    const list = response.data.data.list;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
let timeout = null;
const handleInput = () => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    // 当用户停止输入后，这里发送请求
    fetchSearchResults(searchValue.value);
  }, 300); // 300毫秒防抖时间
};

const fetchSearchResults = async (query: string) => {
  try {
    const response = await axios.get('/api/user/getItems', {
      params: { name: query },
    });
    // 处理响应数据
    console.log(response.data);
    const list = response.data.data.list;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (error) {
    console.error('Error fetching search results:', error);
  } finally {
    dataLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
.list-card {
  height: 100%;

  &-operation {
    display: flex;
    justify-content: space-between;
    margin-bottom: var(--td-comp-margin-xxl);
    flex-direction: row;

    .button {
      margin-right: 5px;
    }

    .search-input {
      width: 360px;
    }
  }

  &-item {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);

    :deep(.t-card__header) {
      padding: 0;
    }

    :deep(.t-card__body) {
      padding: 0;
      margin-top: var(--td-comp-margin-xxl);
      margin-bottom: var(--td-comp-margin-xxl);
    }

    :deep(.t-card__footer) {
      padding: 0;
    }
  }

  &-pagination {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);
  }

  &-loading {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
